<?php

namespace common\observer;

use common\model\TaskMemberModel;
use common\model\TaskRelationModel;
use common\service\CommonService;
use common\service\DismantleTaskService;
use common\service\StatusService;
use support\SingletonTrait;
use teamones\dbeventObserver\interfaces\SplSubject;
use teamones\dbeventObserver\interfaces\SplObserver;

/**
 * 主待办任务完成同步到子待办
 */
class TaskStatusSyncToSubTodo implements SplObserver
{
    use SingletonTrait;

    /**
     * @inheritDoc
     * @throws \Throwable
     */
    function update(SplSubject $subject): void
    {
        $updateData = $subject->getSplUpdateData();
        if (!isset($updateData['task_status'])) {
            return;
        }
        $task = $subject->getSubjectData();
        $taskJson = json_decode($task['json'], true);
        // 子待办状态变更,不走此方法
        if (!empty($taskJson['is_sub_todo'])) {
            return;
        }
        $taskFinalStatus = StatusService::getInstance()->getTaskDoneStatus(); // 已完成
        $taskClosedStatus = StatusService::getInstance()->getTaskDefaultClosedStatus(); // 已取消
        if (!in_array($updateData['task_status'], [$taskFinalStatus['id'], $taskClosedStatus['id']])) {
            return;
        }
        $task = $subject->getSubjectData();
        // 查询主待办下面的子待办
        $subTodoList = DismantleTaskService::getInstance()->getDismantleTaskIds([$task['id']], TaskRelationModel::RELATION_TYPE_SUB_TODO);
        if (empty($subTodoList)) {
            return;
        }
        // 同步更改子待办状态
        try {
            $subTaskIds = [];
            $taskUpdateData = [];
            $taskMemberData = [];
            foreach ($subTodoList as $task) {
                $taskUpdateData[] = [
                    'id' => $task['id'],
                    'task_status' => $updateData['task_status']
                ];
                $subTaskIds[] = $task['id'];
            }
            $taskMemberList = model(TaskMemberModel::class)->where(['task_id' => ['IN', $subTaskIds]])->field('id')->select();
            foreach ($taskMemberList as $data) {
                $taskMemberData[] = [
                    'id' => $data['id'],
                    'status' => $updateData['task_status']
                ];
            }
            // 更新待办状态
            CommonService::instance('task')->commonBatchUpdate($taskUpdateData, module_by_code('task'), false);
            // 更新子待办成员状态
            CommonService::instance('task_member')->commonBatchUpdate($taskMemberData, module_by_code('task_member'), false);
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }

}
